import { getToken, removeToken, setToken } from '@/utils/auth';
import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';

interface responseDefault {
	data: any;
}
// 刷新token
async function refreshToken() {
	const ref = getToken(`token_ref`);
	await axios
		.get(`/appspace/v1/users/token`, {
			'headers': {
				'content-type': `application/json;charset=UTF-8`,
				'Authorization': `Bearer ${ref}`
			}
		})
		.then(async f => {
			const res = f.data;
			if (res.succ) {
				await setToken(`token`, res.options.token);
				await setToken(`token_ref`, res.options.refreshToken);
			} else {
				removeToken(`token`);
				removeToken(`token_ref`);
				ElMessage.error(`token获取失败，请重新登录！`);
				window.location.reload();
			}
		})
		.catch(err => {
			console.log(err);
			removeToken(`token`);
			removeToken(`token_ref`);
			ElMessage.error(`token获取失败，请重新登录！`);
			window.location.reload();
		});
}

// 重新刷新当前接口
async function refreshInterface(config: AxiosRequestConfig): Promise<responseDefault | null> {
	let response = null;
	await axios({
		...config
	})
		.then(res => {
			response = res;
		})
		.catch(error => {
			ElMessage.error({
				'message': error.response.data.message
			});
		});
	return response;
}
// 创建一个axios实例
const instance: AxiosInstance = axios.create({
	// 'baseURL':`http://47.95.212.230:8001`,
	'headers': {
		'content-type': `application/json`
	}
});
// 传参序列化  增加token  暂无
instance.interceptors.request.use((config: AxiosRequestConfig) => {
	const token = getToken(`token`);
	if (token) {
		// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
		config.headers!.Authorization = token ? `Bearer ${token}` : ``; // 请求头加上token
	}
	return config;
});
// 返回状态判断（添加响应拦截器）
instance.interceptors.response.use(
	(res: AxiosResponse) => {
		if (res.headers[`content-type`] === `application/octet-stream`) {
			return Promise.resolve(res);
		}
		if (res.data.succ === false) {
			ElMessage.error(res.data.msg);
		}
		return Promise.resolve(res);
	},
	// eslint-disable-next-line consistent-return
	async (error: AxiosError) => {
		let token = await getToken(`token`);
		const { config } = error;
		// 根据返回的状态码来获取相应的提示
		if (error.response && error.response.status) {
			switch (error.response.status) {
				case 400:
					ElMessage.error(`请求出错`);
					break;
				case 401:
					// token 过期
					/*ElMessage.error(`token过期，请重新登录！`);
					removeToken(`token`);
					window.location.href = import.meta.env.VITE_BASE_SSO_URL + `/sso/oauth/logout?redirect_uri=` + window.location.origin;*/
					// await refreshToken();
					// token = await getToken(`DM_tokenAppID`);
					// if (token) {
					// 	// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
					// 	// config.headers!.Authorization = token ? `Bearer ${token}` : ``; // 请求头加上token
					// 	// const res = await refreshInterface(config);
					// 	// // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
					// 	// if (res!.data.succ === false) {
					// 	// 	// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
					// 	// 	ElMessage.error(res!.data.msg);
					// 	// }
					// 	// return Promise.resolve(res);
					// }
					break;
				case 403:
					ElMessage.error({
						'message': `拒绝访问`
					});
					break;
				case 404:
					ElMessage.error({
						'message': `请求错误,未找到该资源`
					});
					break;
				case 500:
					ElMessage.error({
						'message': error.response.data.message
					});
					break;
				default:
					ElMessage.error({
						'message': error.response.data.msg
					});
			}
		}
	}
);

// 返回一个Promise（发送post请求）
export function post(url: string, params: any) {
	return new Promise((resolve, reject) => {
		instance
			.post(url, params)
			.then(response => {
				resolve(response);
			})
			.catch(error => {
				reject(error);
			});
	});
}

// 返回一个Promise(发送get请求)
export function get(url: string, params: any, config?: any) {
	let urlPath = url;
	const getTimestamp = new Date().getTime();
	if (urlPath.indexOf(`?`) !== -1) {
		urlPath = `${urlPath}&tem=${getTimestamp}`;
	} else {
		urlPath = `${urlPath}?tem=${getTimestamp}`;
	}
	return new Promise((resolve, reject) => {
		instance
			.get(urlPath, { 'params': params, ...config })
			.then(response => {
				resolve(response);
			})
			.catch(error => {
				reject(error);
			});
	});
}

// 返回一个Promise（发送delete请求）
export function del(url: string, params: any) {
	return new Promise((resolve, reject) => {
		instance
			.delete(url, { 'params': params })
			.then(response => {
				resolve(response);
			})
			.catch(error => {
				reject(error);
			});
	});
}

// 返回一个Promise（发送put请求）
export function put(url: string, params: any) {
	return new Promise((resolve, reject) => {
		instance
			.put(url, params)
			.then(response => {
				resolve(response);
			})
			.catch(error => {
				reject(error);
			});
	});
}

// 返回一个Promise（发送patch请求）
export function patch(url: string, params: any) {
	return new Promise((resolve, reject) => {
		instance
			.patch(url, params)
			.then(response => {
				resolve(response);
			})
			.catch(error => {
				reject(error);
			});
	});
}
